package com.steakliu.sun.configcenter;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.steakliu.sun.configcenter.api.ConfigCenterConfig;
import com.steakliu.sun.configcenter.api.ConfigCenterService;
import com.steakliu.sun.configcenter.api.ConfigInfoChangeRefresher;
import com.steakliu.sun.spi.annotation.Join;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * 功能说明： nacos配置中心
 * <p>
 * Original @Author: steakliu-刘牌, 2023-02-08  16:06
 * <p>
 * Copyright (C)2020-2022  steakliu All rights reserved.
 */
@Join
public class NacosConfigCenterService implements ConfigCenterService {
    private final Logger LOGGER = LoggerFactory.getLogger(NacosConfigCenterService.class);

    private ConfigService configService;

    @Override
    public String getConfig(ConfigCenterConfig centerConfig) throws Exception {
        String config = configService.getConfig(centerConfig.getConfigId(), centerConfig.getGroup(), 5000);
        //实时监听
        configService.addListener(centerConfig.getConfigId(), centerConfig.getGroup(), new Listener() {
            @Override
            public Executor getExecutor() {
                return null;
            }
            @Override
            public void receiveConfigInfo(String configInfo) {
                //更新本地配置
                //TODO 因为更新配置中心可能需要重启服务，故先不去做，后续有好的思路再做
                ConfigInfoChangeRefresher.refresh(configInfo);
            }
        });
        return config;
    }

    @Override
    public void init(ConfigCenterConfig centerConfig) throws Exception {
        Properties properties = new Properties();
        properties.put("serverAddr", centerConfig.getAddress());
        this.configService = NacosFactory.createConfigService(properties);
    }
}
